In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.
The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.
In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!
We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.
Make sure that you've downloaded the required human and dog datasets:
Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dogImages.
Download the human dataset. Unzip the folder and place it in the home diretcory, at location /lfw.
Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.
In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.
import numpy as np
from glob import glob
# load filenames for human and dog images
human_files = np.array(glob("lfw/*/*"))
dog_files = np.array(glob("dogImages/*/*/*"))
# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.
OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
#Note: I decided to wrap this code into a helper function for later use.
def show_face_cascade(facefile):
# load color (BGR) image
img = cv2.imread(facefile)
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade.detectMultiScale(gray)
# print number of faces detected in the image
print('Number of faces detected:', len(faces))
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),8)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
show_face_cascade(human_files[0])
Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.
In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.
We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0
Question 1: Use the code cell below to test the performance of the face_detector function.
human_files have a detected human face? dog_files have a detected human face? Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.
Answer: (You can print out your results and/or write your percentages in this cell)
from tqdm import tqdm
human_files_short = human_files[:100]
dog_files_short = dog_files[:100]
#-#-# Do NOT modify the code above this line. #-#-#
## TODO: Test the performance of the face_detector algorithm
## on the images in human_files_short and dog_files_short.
num_faces_human=0
bad_humans=[]
for file in tqdm(human_files_short):
if face_detector(file):
num_faces_human += 1
else:
bad_humans.append(file)
num_faces_dog=0
bad_dogs=[]
for file in tqdm(dog_files_short):
if face_detector(file):
num_faces_dog += 1
bad_dogs.append(file)
print(f"{num_faces_human}% of the first 100 human files have a detected human face.")
print(f"{num_faces_dog}% of the first 100 dog files have a detected human face.")
Actually if you look at some of the dog files in which faces were found, there are actually some human faces in some of them! See:
(note: if you run this yourself then depending on your random seed you may or may not see what I mean here)
for file in bad_dogs: show_face_cascade(file)
Okay but there are definitely also some bogus faces getting selected out of dog faces or strangely face-like dog-fat-wrinkles.
And here are the few humans who just don't look human enough for the face detector:
for file in bad_humans: show_face_cascade(file)
We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.
### (Optional)
### TODO: Test performance of anotherface detection algorithm.
### Feel free to use as many code cells as needed.
# Okay, how about appending a face detector to a CNN that was pretrained on ImageNet?
#Let me start by pulling in a pre-trained VGG16 just like in Step 2 below.
import torch
import torchvision.models as models
# define VGG16 model
human_dog_net = models.vgg16(pretrained=True)
# check if CUDA is available
use_cuda = torch.cuda.is_available()
# move model to GPU if CUDA is available
if use_cuda:
human_dog_net = human_dog_net.cuda()
print(human_dog_net)
Now let's replace the linear layers at the end by our own classifer. Since all it needs to do in the end is "face" and "not face", it doesn't need to be quite as complex as the current VGG16 classifier.
Since we actually don't have that much data to train on (compared to ImageNet!), we should definitely freeze the convolutional layers of VGG16. Otherwise I would be afraid of overfitting.
from torch import nn
human_dog_net.classifier = nn.Sequential(nn.Linear(25088,4096),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(4096,512),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(512,3),
nn.LogSoftmax(dim=1),
)
# Freeze parameters in convolutional layers:
for module in human_dog_net.features:
for param in module.parameters():
param.requires_grad = False
# Need to do this again after defining new classifier module
if use_cuda:
human_dog_net = human_dog_net.cuda()
Now the human_files and dog_files are a bit misleading to train on, since many of the dog_files contain humans. In the end, we want the app to behave a certain way if it detects a dog, a certain way if it detects a human and no dog, and another way if it detects neither. So there are three classes to deal with here.
Ideally I'd want to train on data that has three labels "there is dog", "there is human and no dog", and "there is no human and no dog". But I don't have data of the third type available, and I would need it to be really varied across all the nonhuman nondog possibilities.
I cannot exclude the third category! To do so would make my dog detector be more likely to detect dogs in the absence of a human, and it would make my human detector more likely to detect humans in the absence of a dog. It would correlate 'dogness' to the absence of a human, and 'humanness' to the absence of a dog.
Finding a varied dataset of nonhuman nondogs is a bit harder than it sounds. The labeled image datasets I can find tend to have some humans showing up in all kinds of different categories. (Makes sense. All photos are taken by humans, and humans like to put themselves in photos.)
Okay I will use the dataset here and use the Haar cascade face detector to clean it up! I downloaded and extracted 101_ObjectCategories.tar.gz. Now let's clean it up of as many human faces as possible. To make things run faster (and to avoid what appeared to be opencv bugs related to the size of the image), I deleted any files bigger than 300K using the following bash command:
find 101_ObjectCategories/ -size +300k -type f -delete
There were only 3 such files anyway. I also want to get rid of all files that explicitly contain dogs, so
rm -rf 101_ObjectCategories/dalmatian/ 101_ObjectCategories/snoopy/
(Even though snoopy is a cartoon dog, he's got to go!)
caltech_files = np.array(glob("101_ObjectCategories/*/*"))
haar_faces=[]
for file in tqdm(caltech_files):
if face_detector(file):
haar_faces.append(file)
# Run this cell to save haar_faces list so you don't have to run the above cell to compute it again later.
import pickle
pickle.dump(haar_faces, open( "haar_faces.p", "wb" ))
# Run this cell to load saved haar_faces list if you already produced it before.
import pickle
haar_faces = pickle.load( open( "haar_faces.p", "rb" ) )
I'm going to kick out all the things in the list haar_faces. This does unfortunately kick out a few false faces:
show_face_cascade('101_ObjectCategories/kangaroo/image_0016.jpg')
show_face_cascade('101_ObjectCategories/airplanes/image_0324.jpg')
show_face_cascade('101_ObjectCategories/butterfly/image_0084.jpg')
But the vast majority of things kicked out do actually involve faces, and this does clean up the data quite a bit. We still have a good number of images:
print(len([f for f in caltech_files if f not in haar_faces]))
# 0 will stand for no human and no dog. 1 will still for dog. 2 will stand for human and no dog.
# Defining my own dataloader based on the lists human_files and dog_files
from PIL import Image
from torchvision import transforms
data=[(f,2) for f in human_files[100:]]+[(f,1) for f in dog_files[100:]]+[(f,0) for f in caltech_files if f not in haar_faces]
np.random.shuffle(data)
split_index=int(len(data)*0.1) # 10% of data is reserved for validation
validation_files = data[:split_index]
training_files = data[split_index:]
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
unnormalize = transforms.Normalize(mean=-np.array(normalize.mean) * (1/np.array(normalize.std)),
std=1/np.array(normalize.std))
testing_transformation = transforms.Compose([transforms.Resize((224,224)),
transforms.ToTensor(),
normalize])
training_transformation = transforms.Compose([transforms.RandomRotation(10),
transforms.RandomResizedCrop(224,scale=(0.8,1)),
transforms.ToTensor(),
normalize])
def dataloader(files_labels, transformation, batch_size=32):
"""
Returns a generator that yields pairs (torch tensor of batch of images,torch tensor of batch of labels)
files_labels: A list of pairs consisting of an image filepath and an integer label
transformation: A torchvision transforms transformation.
"""
np.random.shuffle(files_labels)
num_batches = int(len(files_labels)/batch_size)
files_labels=files_labels[:num_batches*batch_size]
for i in range(num_batches):
this_batch = files_labels[i*batch_size:(i+1)*batch_size]
list_of_images = []
for file,_ in this_batch:
try:
img = transformation(Image.open(file).convert('RGB')).unsqueeze(dim=0)
except OSError:
print(f"Image failed to load: {file}")
list_of_images.append(img)
images = torch.cat(list_of_images,dim=0)
labels = torch.from_numpy(np.array([label for _,label in this_batch]))
yield images,labels
Now let me just test out the data loader a bit below:
l=dataloader(training_files,training_transformation)
imgs,lbls=next(l)
plt.imshow((unnormalize(imgs[0]).permute(1,2,0)))
print(lbls[0].item())
Now to test that feedforward even works:
imgs,lbls=next(l)
if use_cuda:
imgs=imgs.cuda()
lbls=lbls.cuda()
torch.exp(human_dog_net(imgs[:1]))
Now for training
from torch import optim
import sys
optimizer=optim.SGD(human_dog_net.classifier.parameters(),lr=0.001)
loss_fn = nn.NLLLoss()
total_training_imgs=len(training_files)
total_validation_imgs=len(validation_files)
# If you don't want to wait for training, skip this cell, download the model I trained, and run the next cell instead.
epochs = 10
min_validation_loss=np.inf
for e in range(epochs):
human_dog_net.train()
total_loss = 0.
imgs_processed = 0
for imgs, lbls in dataloader(training_files,training_transformation):
if use_cuda:
imgs=imgs.cuda()
lbls=lbls.cuda()
optimizer.zero_grad()
loss=loss_fn(human_dog_net(imgs),lbls)
loss.backward()
optimizer.step()
total_loss += loss * imgs.shape[0]
imgs_processed += imgs.shape[0]
sys.stdout.write(f"{imgs_processed}/{total_training_imgs} images processed.\r")
sys.stdout.flush()
print(f"Epoch {e} done. ")
print(f"Training loss: {total_loss/imgs_processed}")
human_dog_net.eval()
total_loss = 0.
num_correct=0
imgs_processed = 0
for imgs, lbls in dataloader(validation_files,testing_transformation):
if use_cuda:
imgs=imgs.cuda()
lbls=lbls.cuda()
with torch.no_grad():
predictions=human_dog_net(imgs)
num_correct+=torch.sum(predictions.argmax(1)==lbls).item()
loss=loss_fn(predictions,lbls)
total_loss += loss * imgs.shape[0]
imgs_processed += imgs.shape[0]
sys.stdout.write(f"{imgs_processed}/{total_validation_imgs} images processed.\r")
sys.stdout.flush()
validation_loss=total_loss/imgs_processed
print(f"Validation loss: {validation_loss}\n")
print(f"Validation accuracy: {100*num_correct/float(imgs_processed)}%\n")
if validation_loss < min_validation_loss:
torch.save(human_dog_net.state_dict(),'human_dog_net.pt')
min_validation_loss = validation_loss
human_dog_net.load_state_dict(torch.load('human_dog_net.pt', map_location='cuda' if use_cuda else 'cpu'))
#Run this cell to just get validation accuracy
human_dog_net.eval()
total_loss = 0.
num_correct=0
imgs_processed = 0
for imgs, lbls in dataloader(validation_files,testing_transformation):
if use_cuda:
imgs=imgs.cuda()
lbls=lbls.cuda()
with torch.no_grad():
predictions=human_dog_net(imgs)
predictions.argmax(1)
num_correct+=torch.sum(predictions.argmax(1)==lbls).item()
loss=loss_fn(predictions,lbls)
total_loss += loss * imgs.shape[0]
imgs_processed += imgs.shape[0]
sys.stdout.write(f"{imgs_processed}/{total_validation_imgs} images processed.\r")
sys.stdout.flush()
print(f"Validation loss: {total_loss/imgs_processed}\n")
print(f"Validation accuracy: {100*num_correct/float(imgs_processed)}%\n")
# Playing with the predictions. Keep running this cell and be amazed!
import random
human_dog_net.eval()
file,lbl = random.choice(validation_files)
img = testing_transformation(Image.open(file).convert('RGB')).unsqueeze(dim=0)
if use_cuda:
img = img.cuda()
pred=human_dog_net(img).argmax().item()
img = img.cpu()
plt.imshow((unnormalize(img.squeeze(dim=0)).permute(1,2,0)))
idx2text={0:'No human, no dog',1:'Dog present',2:'Human present and no dog present'}
print(f"Prediction:{idx2text[pred]}\nLabel:{idx2text[lbl]}")
# Now let's try the initial 100 again since it's asked for in the instructions
# face_detector2 is my alternative face detector for this project.
def face_detector2(file):
img = testing_transformation(Image.open(file).convert('RGB')).unsqueeze(dim=0)
if use_cuda:
img = img.cuda()
human_dog_net.eval()
return human_dog_net(img).argmax().item()==2
num_faces_human=0
bad_humans=[]
for file in tqdm(human_files_short):
if face_detector2(file):
num_faces_human += 1
else:
bad_humans.append(file)
num_faces_dog=0
bad_dogs=[]
for file in tqdm(dog_files_short):
if face_detector2(file):
num_faces_dog += 1
bad_dogs.append(file)
print(f"{num_faces_human}% of the first 100 human files have a detected human face.")
print(f"{num_faces_dog}% of the first 100 dog files have a detected human face.")
Yay I have an improved face detector for the purposes of this project! It runs a lot slower, but that's fine. This isn't needed for processing lots of data-- users would only put in one image at a time, and for that accuracy is more valuable than saving a couple of seconds.
In this section, we use a pre-trained model to detect dogs in images.
The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.
import torch
import torchvision.models as models
# define VGG16 model
VGG16 = models.vgg16(pretrained=True)
# check if CUDA is available
use_cuda = torch.cuda.is_available()
# move model to GPU if CUDA is available
if use_cuda:
VGG16 = VGG16.cuda()
Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.
In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.
Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.
Note to reader: The transforms used in the following implentation were defined up in the cell where I defined my dataloader for human_dog_net.
from PIL import Image
import torchvision.transforms as transforms
def VGG16_predict(img_path):
'''
Use pre-trained VGG-16 model to obtain index corresponding to
predicted ImageNet class for image at specified path
Args:
img_path: path to an image
Returns:
Index corresponding to VGG-16 model's prediction
'''
## TODO: Complete the function.
## Load and pre-process an image from the given img_path
## Return the *index* of the predicted class for that image
VGG16.eval()
img = testing_transformation(Image.open(img_path).convert('RGB')).unsqueeze(dim=0)
if use_cuda:
img = img.cuda()
return VGG16(img).argmax().item() # predicted class index
While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).
Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
## TODO: Complete the function.
prediction = VGG16_predict(img_path)
return prediction>=151 and prediction<=268 # true/false
Question 2: Use the code cell below to test the performance of your dog_detector function.
human_files_short have a detected dog? dog_files_short have a detected dog?Answer: (My answer is printed in the output of the cell below.)
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
num_dogs_human=0
bad_humans=[]
for file in tqdm(human_files_short):
if dog_detector(file):
num_dogs_human += 1
bad_humans.append(file)
num_dogs_dog=0
bad_dogs=[]
for file in tqdm(dog_files_short):
if dog_detector(file):
num_dogs_dog += 1
else:
bad_dogs.append(file)
print(f"{num_dogs_human}% of the first 100 human files have a detected dog.")
print(f"{num_dogs_dog}% of the first 100 dog files have a detected dog.")
I'm curious about any humans photos that triggered the dog detector! Let's see one:
imagenet_classes = pickle.load(open('imagenet1000_clsid_to_human.pkl','rb'))
for file in human_files:
if dog_detector(file):
plt.imshow(Image.open(file).convert('RGB'))
plt.show()
print(f"A \"{imagenet_classes[VGG16_predict(file)]}\" was detected in the above image.")
break
We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.
### (Optional)
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.
Okay, my answer to the optional part of step 1 actually does include a dog detector! So let me go ahead define the dog detector portion of it and and and print the test results for that here.
(But I'm using VGG16 with just some additional training on my dataset, so I would not expect this to be much better than the using pretrained VGG16 directly as above).
# dog_detector2 is my alternative dog detector for this project.
def dog_detector2(file):
img = testing_transformation(Image.open(file).convert('RGB')).unsqueeze(dim=0)
if use_cuda:
img = img.cuda()
human_dog_net.eval()
return human_dog_net(img).argmax().item()==1
num_dogs_human=0
bad_humans=[]
for file in tqdm(human_files_short):
if dog_detector(file):
num_dogs_human += 1
bad_humans.append(file)
num_dogs_dog=0
bad_dogs=[]
for file in tqdm(dog_files_short):
if dog_detector(file):
num_dogs_dog += 1
else:
bad_dogs.append(file)
print(f"{num_dogs_human}% of the first 100 human files have a detected dog.")
print(f"{num_dogs_dog}% of the first 100 dog files have a detected dog.")
Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.
We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.
| Brittany | Welsh Springer Spaniel |
|---|---|
![]() |
![]() |
It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).
| Curly-Coated Retriever | American Water Spaniel |
|---|---|
![]() |
![]() |
Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.
| Yellow Labrador | Chocolate Labrador | Black Labrador |
|---|---|---|
![]() |
![]() |
![]() |
We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.
Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!
Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!
import os,torch
from torchvision import datasets,transforms
### TODO: Write data loaders for training, validation, and test sets
## Specify appropriate transforms, and batch_sizes
image_size=192
batch_size=64
def randomCroppedRotateResize(max_angle,final_size):
"""A transformation that rotates the image by a random angle in range [-max_angle, +max_angle)
then crops just enough to get rid of the empty black triangles in the border and resizes
image to be a square of size final_size on each side. The angle should be given in degrees."""
def f(img):
angle=np.random.random()*2.0*max_angle-max_angle
theta = np.abs(np.radians(angle))
size_before_rot = final_size * (1+np.tan(theta))**2 / (1+np.tan(theta)**2)
size_before_rot = int(size_before_rot+1)
img=transforms.functional.resize(img,(size_before_rot,size_before_rot))
img=transforms.functional.rotate(img,angle)
img=transforms.functional.center_crop(img,final_size)
return img
return f
testing_transformation = transforms.Compose([transforms.Resize((image_size,image_size)),
transforms.ToTensor()])
training_transformation = transforms.Compose([
# transforms.Resize((image_size,image_size)),
randomCroppedRotateResize(10,image_size),
transforms.RandomGrayscale(p=0.1),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomVerticalFlip(p=0.5),
transforms.ColorJitter(brightness=0.2,contrast=0.2),
transforms.ToTensor(),
])
training_dataloader = torch.utils.data.DataLoader(
datasets.ImageFolder('dogImages/train/',transform=training_transformation),
batch_size=batch_size,
shuffle=True)
validation_dataloader = torch.utils.data.DataLoader(
datasets.ImageFolder('dogImages/valid/',transform=testing_transformation),
batch_size=batch_size)
test_dataloader = torch.utils.data.DataLoader(
datasets.ImageFolder('dogImages/test/',transform=testing_transformation),
batch_size=batch_size)
loaders_scratch = {'train':training_dataloader,
'valid':validation_dataloader,
'test' :test_dataloader }
#just making sure of something here...
assert(training_dataloader.dataset.class_to_idx == validation_dataloader.dataset.class_to_idx)
assert(training_dataloader.dataset.class_to_idx == test_dataloader.dataset.class_to_idx)
Question 3: Describe your chosen procedure for preprocessing the data.
Answer:
How the code resizes:
It uses a transformation I wrote randomCroppedRotateResize, which rotates the image by a random angle and the resizes the image down to image_size. The special thing about this transformation is that it actually does a crop as well, and it crops out exactly what it needs to in order to get rid of the black triangles that appear after a rotation. Bigger angles thus lead to bigger cropping, and I don't want to crop out any dogs so the angle is limited to $\pm 10^\circ$. The image_size is set to 192 for $192\times 192$ images. At first I tried 128, but after looking at the data myself (using the cell below) I decided that certain helpful finer features (such as fur textures) were being overly blurred for some dogs. I chose 192 specifically because I like powers of 2 (they make it easier for me to think through maxpooling steps): $192=3\cdot 2^6$. The size 256 is larger than I need, I think.
Other transformations: I chose to augment my data with a lot of different random transformations. The main reason is that I just don't have that much data for this task, and augmenting can allow me to train a more complex model without worrying as much about overfitting to a small data set.
The RandomGrayscale is there to prevent the model from relying too much on color all the time. Of course it will need to rely on color information a lot, but I want aspects of it to train that can get as much as possible without necessarily having color information. This is effectively like having dropout, except it's specifically focused on neurons that detect color.
The random horizantal and vertical flips are there because dogs are chirally symmetric objects, as far as I know. Vertical flips are maybe a bit more silly since people are likely to input upright dogs into this thing... but I'd like to go for as much robustness as possible against the rotational setup of the dog.
The small brightness and contrast variations should be harmless to feature detection and augment my data.
Normalization:
I chose not to apply any normalization. transforms.ToTensor already forces things into the [0,1] range, and that's good enough for me.
#Look at some training data here
class_to_idx = training_dataloader.dataset.class_to_idx
idx_to_class = {idx:cls for cls,idx in class_to_idx.items()}
imgs,lbls=next(iter(training_dataloader))
plt.imshow((imgs[0].permute(1,2,0)))
print(idx_to_class[lbls[0].item()])
Create a CNN to classify dog breed. Use the template in the code cell below.
import torch.nn as nn
import torch.nn.functional as F
# define the CNN architecture
class Net(nn.Module):
### TODO: choose an architecture, and complete the class
def __init__(self):
super(Net, self).__init__()
## Define layers of a CNN
# self.image_size=size
self.conv1_1=nn.Conv2d(3,64,3,padding=1)
self.conv2_1=nn.Conv2d(64,64,3,padding=1)
self.lin1 =nn.Linear(65536,512)
self.lin2 =nn.Linear(512,133)
self.mp2 = nn.MaxPool2d(2,2)
self.mp3 = nn.MaxPool2d(3,3)
self.do = nn.Dropout(p=0.5)
self.act= nn.ReLU()
def forward(self, x):
x=self.conv1_1(x)
x=self.mp2(x)
x=self.act(x)
x=self.conv2_1(x)
x=self.mp3(x)
x=self.act(x)
x=x.view(-1,65536)
x=self.do(self.act(self.lin1(x)))
x=nn.LogSoftmax(dim=1)(self.lin2(x))
return x
#-#-# You do NOT have to modify the code below this line. #-#-#
# instantiate the CNN
model_scratch = Net()
# move tensors to GPU if CUDA is available
if use_cuda:
model_scratch.cuda()
Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.
Answer:
My first approach was to try a scaled down version of VGG16. I know it of course needs to be scaled down, since I have a lot less data to work with than ImageNet! But I didn't scale it down nearly enough! It was training so slowly that I doubted my training code and loaded in MNIST data to test it on. It worked just fine on MNIST, so I guess it was just training really slowly on the dog images.
I finally scaled my model down enough to see some training progress, only to start overfitting like crazy. My model was still too huge for the data!
I continued to scale things down until I stopped seeing overfitting, until I was down to trying 2-3 convolutional layers followed by 1-2 fully connected layers. I imposed heavy dropout in the hidden linear layer to help fight the overfitting.
At that point I could continue to fine-tune the number of parameters in my model by
But I couldn't get things quite right... I would either overfit (when I increase the number of parameters) or converge too early (when I allow too few parameters). The best I could get was 9% test accuracy.
At that point I looked up how to get $L_2$ regularization to work, and ended up reading documentation on the weight_decay hyperparameter in the SGD optimizer. (BTW I like SGD because I understand it. I might try different optimizers later, but I don't understand Adam yet, for example.)
I ended finding a happy-medium number of parameters where I got some overfitting, but only later in the training. Then I fixed that model and starting tuning weight_decay until I found a good value that didn't supress training too much and didn't let overfitting slip through so early on. The training still slips past the regularization and overfits eventually, but not before giving me a good enough model with 14% test accuracy! Yay?
The training output below shows the result of 100 epochs, but I actually trained for 180 just for fun. It didn't matter because overfitting had started by around epoch 40.
I think the main issue with training a CNN from scratch here is that we just have too little data to get the performance we want. It might be fine if there were just a handful of classes, but choosing correctly out of 133 classes requires a great deal of accuracy on the part of the model. Borrowing a diagram from the udacity notes,

we are in a situation where we have limited training data, and the data (while specific) is similar to the ImageNet type data. So we really should be doing transfer-learning in which almost the entire pretrained model is frozen!
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.
import torch.optim as optim
### TODO: select loss function
criterion_scratch = nn.NLLLoss()
### TODO: select optimizer
optimizer_scratch = optim.SGD(model_scratch.parameters(),lr=0.02,momentum=0.9,weight_decay=0.002)
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.
from timeit import default_timer as timer
from datetime import timedelta
import numpy as np
import sys
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
"""returns trained model"""
# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
num_train_imgs=len(loaders['train'])*loaders['train'].batch_size
num_valid_imgs=len(loaders['valid'])*loaders['valid'].batch_size
for epoch in range(1, n_epochs+1):
# initialize variables to monitor training and validation loss
train_loss = 0.0
valid_loss = 0.0
start_time = timer()
###################
# train the model #
###################
model.train()
for batch_idx, (data, target) in enumerate(loaders['train']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
## find the loss and update the model parameters accordingly
## record the average training loss, using something like
## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
optimizer.zero_grad()
loss=criterion(model(data),target)
loss.backward()
optimizer.step()
train_loss += ((1 / (batch_idx + 1)) * (loss.item() - train_loss)) #this is clever!
sys.stdout.write("Processed "+str(batch_idx*loaders['train'].batch_size)+'/'+str(num_train_imgs)+' \r')
sys.stdout.flush()
######################
# validate the model #
######################
model.eval()
num_correct=0
for batch_idx, (data, target) in enumerate(loaders['valid']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
## update the average validation loss
with torch.no_grad():
output=model(data)
loss=criterion(output,target)
num_correct+=torch.sum(output.argmax(1)==target).item()
valid_loss += ((1 / (batch_idx + 1)) * (loss.item() - valid_loss))
sys.stdout.write("Processed "+str(batch_idx*loaders['valid'].batch_size)+'/'+str(num_valid_imgs)+' \r')
sys.stdout.flush()
# print training/validation statistics
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}\t Validation Acc: {}'.format(
epoch,
train_loss,
valid_loss,
num_correct/float(num_valid_imgs)
))
## TODO: save the model if validation loss has decreased
if valid_loss<valid_loss_min:
torch.save(model.state_dict(),save_path)
valid_loss_min=valid_loss
epoch_time = timer() - start_time
print(f'That took {timedelta(seconds=epoch_time)}.\
Estimated time remaining: {timedelta(seconds=epoch_time*(n_epochs-epoch))}\n')
# return trained model
return model
# train the model
model_scratch = train(180, loaders_scratch, model_scratch, optimizer_scratch,
criterion_scratch, use_cuda, 'model_scratch.pt')
# load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
# I run this cell when I want to load the model without having to retrain it.
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.
def test(loaders, model, criterion, use_cuda):
# monitor test loss and accuracy
test_loss = 0.
correct = 0.
total = 0.
model.eval()
for batch_idx, (data, target) in enumerate(loaders['test']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the loss
loss = criterion(output, target)
# update average test loss
test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
# convert output probabilities to predicted class
pred = output.data.max(1, keepdim=True)[1]
# compare predictions to true label
correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
total += data.size(0)
print('Test Loss: {:.6f}\n'.format(test_loss))
print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
100. * correct / total, correct, total))
# call test function
test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
# Setting up to play with model:
class_to_idx = test_dataloader.dataset.class_to_idx
idx_to_class = {idx:cls for cls,idx in class_to_idx.items()}
l=iter(test_dataloader)
# Play with model:
imgs,lbls=next(l)
ii=np.random.randint(0,imgs.shape[0]-1)
img=imgs[ii]
lbl=lbls[ii]
plt.imshow((img.permute(1,2,0)))
if use_cuda: img=img.cuda()
with torch.no_grad():
pred=torch.exp(model_scratch(img.unsqueeze(dim=0)))
probabilities,classes=pred.squeeze().topk(5,sorted=True)
classes=classes.cpu()
print("Actual breed: "+str(idx_to_class[lbl.item()]))
class_names = [idx_to_class[idx] for idx in classes.data.numpy().tolist()]
print("Top 5 predictions in order:\n"+str(class_names))
You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.
Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).
If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.
## TODO: Specify data loaders
# I like my data loaders from earlier but the image size needs to be made compatible for VGG,
# so I am copying the code and only modifying image_size
# and adding the normalization that VGG was trained on
image_size=224
batch_size=64
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
unnormalize = transforms.Normalize(mean=-np.array(normalize.mean) * (1/np.array(normalize.std)),
std=1/np.array(normalize.std))
testing_transformation = transforms.Compose([transforms.Resize((image_size,image_size)),
transforms.ToTensor(),
normalize,])
training_transformation = transforms.Compose([
# transforms.Resize((image_size,image_size)),
randomCroppedRotateResize(10,image_size),
transforms.RandomGrayscale(p=0.1),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomVerticalFlip(p=0.5),
transforms.ColorJitter(brightness=0.2,contrast=0.2),
transforms.ToTensor(),
normalize,
])
training_dataloader = torch.utils.data.DataLoader(
datasets.ImageFolder('dogImages/train/',transform=training_transformation),
batch_size=batch_size,
shuffle=True)
validation_dataloader = torch.utils.data.DataLoader(
datasets.ImageFolder('dogImages/valid/',transform=testing_transformation),
batch_size=batch_size)
test_dataloader = torch.utils.data.DataLoader(
datasets.ImageFolder('dogImages/test/',transform=testing_transformation),
batch_size=batch_size)
loaders_transfer = {'train':training_dataloader,
'valid':validation_dataloader,
'test' :test_dataloader }
Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.
import torchvision.models as models
import torch.nn as nn
# check if CUDA is available
use_cuda = torch.cuda.is_available()
## TODO: Specify model architecture
model_transfer = models.vgg16(pretrained=True)
if use_cuda:
model_transfer = model_transfer.cuda()
# Freeze parameters in convolutional layers:
for module in model_transfer.features:
for param in module.parameters():
param.requires_grad = False
#Look at classifier layers:
model_transfer.classifier
# Freeze parameters in the first fully connected layer:
for param in model_transfer.classifier[0].parameters():
param.requires_grad = False
# Re-initialize the last two fully connected layers with 512 hidden nodes and 133 output nodes
model_transfer.classifier[3]=nn.Linear(4096,512).to('cuda' if use_cuda else 'cpu')
model_transfer.classifier[6]=nn.Linear(512,133).to('cuda' if use_cuda else 'cpu')
# Replace dropout by batch normalization-- I had more success with it.
model_transfer.classifier[2]=nn.BatchNorm1d(4096).to('cuda' if use_cuda else 'cpu')
model_transfer.classifier[5]=nn.BatchNorm1d(512 ).to('cuda' if use_cuda else 'cpu')
# Tack on a log softmax at the end, because I like doing things this way
model_transfer.classifier.add_module("7",nn.LogSoftmax(dim=1))
# Look at the entire thing to make sure things are as expected:
model_transfer
Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.
Answer: For reasons outlined at the end of my answer to question 4, I expect some success from an approach in which I only train the last one or two fully connected layers of the pretrained VGG16. I also should randomize the weights in the layer I'm going to train, to gain the general benefits of well-initialized weights.
Intuitively, the layers of VGG16 are already very good at extracting features from images. My model can learn to classify dog breeds based on these features, rather than also having to learn feature extraction itself. The resulting model will be bigger than it needs to be, since VGG16 extracts a lot of features that are probably irrelevant to dog breed. But it will train much faster and gain higher accuracy than I can get from my small dog breed dataset.
I experimented with the following setups:
I ended up finding that batch normalization worked incredibly well, and that I could get lower validation loss by training the last two hidden layers rather than just one, and that a relatively small number of hidden nodes prevented early overfitting during training.
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.
import torch.optim as optim
criterion_transfer = nn.NLLLoss()
optimizer_transfer = optim.SGD(model_transfer.parameters(),lr=0.02,momentum=0.9)
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.
# train the model
model_transfer = train(10, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt')
# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load('model_transfer.pt'))
Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
threshold = 1 # If the probability on the prediction is below this, we'd like to report the top k predictions.
# (this threshold is giving me info for the flask app I worked out outside of this notebook,
# I changed it to 1 here to give accurate "topk" accuracies)
test_loss = 0.
correct = [0]*5
total = 0
model_transfer.eval()
for batch_idx, (data, target) in enumerate(loaders_transfer['test']):
if use_cuda:
data, target = data.cuda(), target.cuda()
with torch.no_grad():
output = model_transfer(data)
loss = criterion_transfer(output, target)
test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
top5_logprobs, top5_indices = output.topk(5,dim=1,sorted=True)
top5_probs=torch.exp(top5_logprobs)
for n in range(top5_probs.shape[0]):
top_prob=top5_probs[n][0].item()
indices_list = top5_indices[n].cpu().numpy().tolist()
if target[n].item()==top5_indices[n][0].item():
for i in range(len(correct)): correct[i] += 1
elif top_prob<threshold and target[n].item() in indices_list:
for i in range(indices_list.index(target[n].item()),len(correct)): correct[i] += 1
total += data.size(0)
print('Test Loss: {:.6f}\n'.format(test_loss))
print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
100. * correct[0] / total, correct[0], total))
for i in range(1,len(correct)):
print('\nTest \"Top %d\" Accuracy: %2d%% (%2d/%2d)' % (
i+1,100. * correct[i] / total, correct[i], total))
Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from PIL import Image
class_to_idx = training_dataloader.dataset.class_to_idx
idx_to_class = {idx:(cls[4:].replace("_", " ")) for cls,idx in class_to_idx.items()}
pickle.dump(idx_to_class, open( "idx_to_class.p", "wb" )) # this will be handy to have in the flask app
def predict_breed_transfer(img_path):
img = testing_transformation(Image.open(img_path).convert('RGB')).unsqueeze(dim=0)
if use_cuda: img=img.cuda()
model_transfer.eval()
with torch.no_grad():
output = model_transfer(img)
return idx_to_class[output.squeeze(dim=0).argmax().item()]
# Setting up to play with model:
l=iter(test_dataloader)
# Play with model:
imgs,lbls=next(l)
ii=np.random.randint(0,imgs.shape[0]-1)
img=imgs[ii]
lbl=lbls[ii]
plt.imshow((unnormalize(img).permute(1,2,0)))
if use_cuda: img=img.cuda()
with torch.no_grad():
pred=torch.exp(model_transfer(img.unsqueeze(dim=0)))
probabilities,classes=pred.squeeze().topk(5,sorted=True)
classes=classes.cpu()
print("Actual breed: "+str(idx_to_class[lbl.item()]))
class_names = [idx_to_class[idx] for idx in classes.data.numpy().tolist()]
print("Top 5 predictions in order:\n"+str(class_names))
Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,
You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and human_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.
Some sample output for our algorithm is provided below, but feel free to design your own user experience!

### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
human_dog_net_transformation = transforms.Compose([transforms.Resize((224,224)),
transforms.ToTensor(),
normalize])
def run_app(img_path):
img = human_dog_net_transformation(Image.open(img_path).convert('RGB')).unsqueeze(dim=0)
plt.imshow((unnormalize(img.squeeze(dim=0)).permute(1,2,0)))
plt.show()
if use_cuda: img = img.cuda()
human_dog_net.eval()
with torch.no_grad():
human_dog_presence = human_dog_net(img).argmax().item()
if human_dog_presence == 0:
print("I can't find the dog in this image.")
return -1
elif human_dog_presence == 1:
print("I'm pretty sure that's a ...")
elif human_dog_presence == 2:
print("I can't find a dog, but there does seem to be a human in this image!")
print("The image most closely resembles a ...")
print(predict_breed_transfer(img_path)+'.')
return 0
In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?
Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.
Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.
Answer: Since my expectations were pretty much crushed by the attempt to create a good model from scratch, I ended up being very impressed with the final model created with transfer learning. Some improvement ideas:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
## suggested code, below
run_app('sample_images/01.jpg')
print("(The website I pulled this from said that this is an English Sheepdog/Wirehaired Fox Terrier Mix.)")
run_app('sample_images/02.jpg')
print("(As you can see, this is a stuffed toy version of the taco bell chihuahua.)")
run_app('sample_images/03.jpg')
print("(A very nice clear photo of a labrador retriever.)")
run_app('sample_images/04.png')
print("(Jake the dog.)")
run_app('sample_images/05.jpg')
print("(I'm trying to throw off the dog_detector. I don't know what the actual breed is.)")
#Let's do five random humans for fun
for _ in range(5):
run_app(random.choice(human_files))